import {onUnmounted,ref, type Ref} from 'vue'

// 发送验证码

import type { codeType } from "@/types/user";
import { showToast, type FormInstance  } from 'vant';
import {sendMobileCode} from "@/services/user";
import { followOrUnfollow } from '@/services/consult'
import type { FollowType } from '@/types/consult';


export const useMobileCode = (
  mobile:Ref<string> ,
  type:codeType = 'login'
) => {
  const time = ref(0)
  const form = ref<FormInstance>()
  let timer:number  // 0

  const onSend = async ()=>{
    if(time.value > 0) return
    // 验证不通过报错  组织程序继续执行
    await form.value?.validate('mobile')
    await sendMobileCode(mobile.value,'login')
    
    
    showToast('发送成功')
    // 倒计时开启

    time.value = 3

    if(timer) clearInterval(timer)

    timer = setInterval(()=>{
      time.value--
      if(time.value <= 0)clearInterval(timer)
    } , 1000)
  }

  onUnmounted(()=>{
    clearInterval(timer)
  })

  return {onSend , time , form}
}


// 点关注

export const useFollow = (type:FollowType = 'easy')=>{
  const loading = ref(false)

  const follow = async (item:{id:string|number , likeFlag:0|1})=>{
    loading.value = true
    try{
      await followOrUnfollow(item.id , type)
      // 0 '' undedfind  null ---> false
      // 点完按钮之后的  状态值
      item.likeFlag = item.likeFlag===1 ? 0 : 1
    }finally {
      loading.value = false
    }
  }

  return {loading , follow}
}
